package com.syaccp.utils;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;

/**
 * Web网页工具类
 *
 * @author Lyh
 * @since 2023-07-16
 */
public class CheckWebPageUtil {

    /**
     * 检查Web网页是否存在
     *
     * @param url 地址
     * @return true：网页存在  false：网页不存在
     */
    public static boolean checkUrlConnection(String url) {
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json");
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(600)// 设置连接主机服务超时时间
                .setConnectionRequestTimeout(1000)// 设置连接请求超时时间
                .setSocketTimeout(1000)// 设置读取数据连接超时时间
                .build();
        // 添加配置
        httpGet.setConfig(requestConfig);
        // 设置请求头
        CloseableHttpClient httpclient;
        CloseableHttpResponse response;
        int statusCode;
        boolean flag = true;
        httpclient = HttpClients.createDefault();// 创建Httpclient对象
        try {
            // 执行请求
            response = httpclient.execute(httpGet);
            statusCode = response.getStatusLine().getStatusCode();
        } catch (IOException e) {
            return false;
        }
        if (statusCode == 404) flag = false;
        return flag;
    }
}
